package com.ponxu.mb.web.action;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ponxu.log.Log;
import com.ponxu.log.LogFactory;
import com.ponxu.mb.model.Post;
import com.ponxu.mb.service.PostService;
import com.ponxu.utils.Lang;
import com.ponxu.web.core.WebContext;

/**
 * 文章显示
 * 
 * @author xwz
 */
public class PostAction extends MiniBlogAction {
	private static final Log LOG = LogFactory.getLog();
	private static final String FTL_POST = "post.ftl";
	private static final String FTL_ASK_PASSWORD = "/themes/password.ftl";

	// 可查看的文章状态
	private static final List<String> CAN_SHOW_STATUS = Arrays
			.asList(new String[] { "public", "protected" });

	public String execute(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		WebContext context = new WebContext(request, response);
		int id = context.getIntParameter("id");
		String seoTitle = context.getParameter("seotitle");
		LOG.debug("id=%d, seotitle=%s", id, seoTitle);

		Post post = null;
		if (id != 0) {
			post = PostService.getById(id);
		} else if (Lang.isNotEmpty(seoTitle)) {
			post = PostService.getBySeoTitle(seoTitle);
		}

		// 未找到
		if (post == null) {
			return FTL_404;
		}

		// 是否管理员
		boolean isAdmin = context.sessionGet("admin") != null;

		// 不是管理员, 会有限制
		if (!isAdmin) {
			LOG.debug("%d , %s", post.getId(), post.getStatus());
			if (!CAN_SHOW_STATUS.contains(post.getStatus())) {
				return FTL_404;
			}

			// 密码保护
			if ("protected".equalsIgnoreCase(post.getStatus())) {
				String password = context.getParameter("password");
				if (!password.equalsIgnoreCase(post.getPassword())) {
					context.put("post", post);
					return FTL_ASK_PASSWORD;
				}
			}
		}

		context.put("post", post);
		return FTL_POST;
	}
}